package com.example.chirdrenserver.controller;


import com.example.chirdrenserver.Holder.UserHolder;
import com.example.chirdrenserver.Pojo.dto.BasePage;
import com.example.chirdrenserver.Pojo.dto.HistoryDTO;
import com.example.chirdrenserver.Pojo.entity.History;
import com.example.chirdrenserver.Pojo.entity.HistoryMessage;
import com.example.chirdrenserver.Pojo.entity.PostMessage;
import com.example.chirdrenserver.Pojo.vo.HisStoryVO;
import com.example.chirdrenserver.Service.HistoryPostService;
import com.example.chirdrenserver.Service.HistoryService;
import com.example.chirdrenserver.Utils.Result;
import com.example.chirdrenserver.confg.RabbitMQConfig;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @Author: Yu
 * @CreateTime: 2025-07-07
 * @Description:
 */
@RequestMapping("/history")
@RestController
public class HistoryController {
    @Autowired
    HistoryService historyService;

    @Autowired
    HistoryPostService historyPostService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 添加历史记录
     *
     * @param
     * @return
     */
    @PostMapping("/{id}")
    public Result getHistory(@RequestBody HistoryDTO historyDTO) {
        String TaskId = UUID.randomUUID().toString();
        HistoryMessage historyMessage = new HistoryMessage();
        historyMessage.setPostId(historyDTO.getPostId());
        historyMessage.setViewTime(LocalDateTime.now());
        historyMessage.setUserId(UserHolder.get());
        historyMessage.setTaskId(TaskId);
        sendMessage(TaskId, historyMessage);
        return Result.success();
    }

    /**
     * 查看历史纪律
     *
     * @return
     */
    @PostMapping("/list")
    public Result<HisStoryVO> getHistory(@RequestBody BasePage basePage) {

        return Result.success();
    }

    @PostMapping("/clean")
    public Result cleanHistory() {

        return Result.success();
    }

    private boolean sendMessage(String taskId, HistoryMessage historyMessage) {
        // 发送到RabbitMQ
        rabbitTemplate.convertAndSend(
                RabbitMQConfig.HISTORY_EXCHANGE,
                RabbitMQConfig.HISTORY_ROUTING_KEY,
                historyMessage,
                m -> {
                    // 设置消息属性
                    m.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);//消息持久化
                    m.getMessageProperties().setCorrelationId(taskId);
                    m.getMessageProperties().setHeader("taskId", taskId);

                    return m;
                }
        );
        return true;
    }
}
